package com.renge.eduservice.entity.easyExcel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.renge.eduservice.entity.EduSubject;
import com.renge.eduservice.service.EduSubjectService;
import com.renge.exception.GuliException;

import java.util.Map;

public class SubjectExcelListen  extends AnalysisEventListener<SubjectData> {
    //把eduSubjectService引进来方便数据库操作
    private EduSubjectService eduSubjectService;
    public SubjectExcelListen(){
    }
    public SubjectExcelListen(EduSubjectService eduSubjectService){
          this.eduSubjectService= eduSubjectService;
    }
    //一行一行读取excel内容
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext context) {
        String subjectOne = subjectData.getSubjectOne();  //获得一级分类
        //读到的一级分类不能为空
        if(subjectOne==null){
            throw new GuliException();
        }
        //如果title不相同，添加进数据库
        EduSubject oneEduSubject = getOneEduSubject(subjectOne);
        if(oneEduSubject==null){
            oneEduSubject = new EduSubject();
            oneEduSubject.setTitle(subjectOne);
            oneEduSubject.setParentId("0");
            eduSubjectService.save(oneEduSubject);
        }

        String subjectTwo = subjectData.getSubjectTwo();  //获得二级分类
        //读到的二级分类不能为空
        if(subjectTwo==null){
            throw new GuliException();
        }
        EduSubject twoEduSubject = getTwoEduSubject(subjectTwo, oneEduSubject.getId());
        if(twoEduSubject==null){
            twoEduSubject = new EduSubject();
            twoEduSubject.setTitle(subjectTwo);
            twoEduSubject.setParentId(oneEduSubject.getId());
            eduSubjectService.save(twoEduSubject);
        }

    }
    //验证一级分类没有重复
    public EduSubject getOneEduSubject(String title){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("title",title);
        queryWrapper.eq("parent_id","0");
        return  eduSubjectService.getOne(queryWrapper);
    }
    //验证二级分类没有重复
    public EduSubject getTwoEduSubject(String title,String parentid){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("title",title);
        queryWrapper.eq("parent_id",parentid);
        return  eduSubjectService.getOne(queryWrapper);
    }
    //读取表头内容
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {

    }

    //读取完成之后
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}
